/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.cms.column.service;

import com.jeeplus.cms.util.CmsCacheUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.service.TreeService;
import com.jeeplus.modules.cms.column.entity.CmsColumn;
import com.jeeplus.modules.cms.column.mapper.CmsColumnMapper;
import com.jeeplus.modules.cms.content.entity.CmsContents;
import com.jeeplus.modules.cms.content.service.CmsContentsService;
import com.jeeplus.modules.cms.contenttype.entity.CmsContentType;
import com.jeeplus.modules.cms.contenttype.service.CmsContentTypeService;
import com.jeeplus.modules.cms.site.entity.CmsSite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 栏目Service
 *
 * @author Sawyer
 * @version 2020-11-21
 */
@Service
@Transactional(readOnly = true)
public class CmsColumnService extends TreeService<CmsColumnMapper, CmsColumn> {

    @Autowired
    private CmsContentsService contentsService;

    @Autowired
    private CmsContentTypeService contentTypeService;

    @Override
    public CmsColumn get(String id) {
        return super.get(id);
    }

    @Override
    public List<CmsColumn> findList(CmsColumn cmsColumn) {
        if (StringUtils.isNotBlank(cmsColumn.getParentIds())) {
            cmsColumn.setParentIds("," + cmsColumn.getParentIds() + ",");
        }
        return super.findList(cmsColumn);
    }

    @Transactional(readOnly = false)
    @Override
    public void save(CmsColumn cmsColumn) {
        // 新增记录时初始化数据
        if (null == cmsColumn.getId()) {
            cmsColumn.init();
        }
        super.save(cmsColumn);

        // 清除缓存
        CmsCacheUtils.removeCacheBySiteId(CmsCacheUtils.COLUMN_LIST_CACHE, cmsColumn.getSiteId());
    }

    @Transactional(readOnly = false)
    @Override
    public void delete(CmsColumn cmsColumn) {
        // 子节点
        List<CmsColumn> children = mapper.getChildren(cmsColumn.getId());
        if (null != children && children.size() > 0) {
            throw new RuntimeException(String.format("栏目[%s]下含有子节点[%s]", cmsColumn.getId(), children.get(0).getName()));
        }

        // 发布内容
        CmsContents cmsContents = new CmsContents();
        cmsContents.setColumnId(cmsColumn.getId());
        List<CmsContents> contentsList = contentsService.findList(cmsContents);
        if (null != contentsList && contentsList.size() > 0) {
            throw new RuntimeException(String.format("栏目[%s]已被内容[%s]关联", cmsColumn.getId(), contentsList.get(0).getTitle()));
        }

        // 类型
        CmsContentType contentType = new CmsContentType();
        contentType.setColumn(cmsColumn);
        List<CmsContentType> contentTypeList = contentTypeService.findList(contentType);
        if (null != contentTypeList && contentTypeList.size() > 0) {
            throw new RuntimeException(String.format("栏目[%s]已被类型[%s]关联", cmsColumn.getId(), contentTypeList.get(0).getName()));
        }

        final String siteId = get(cmsColumn.getId()).getSiteId();
        super.delete(cmsColumn);
        // 清除缓存
        CmsCacheUtils.removeCacheBySiteId(CmsCacheUtils.COLUMN_LIST_CACHE, siteId);
    }

    @Transactional(readOnly = false)
    public void updateHitsAddOne(String id) {
        mapper.updateHitsAddOne(id);

        for (CmsSite site : CmsCacheUtils.getSiteListByCache()) {
            Optional<CmsColumn> optional = CmsCacheUtils.getColumnListByCache(site.getId(), false)
                    .stream()
                    .filter(item -> id.equals(item.getId()))
                    .findFirst();

            if (optional.isPresent()) {
                optional.get().setHits(null == optional.get().getHits() ? 1 : optional.get().getHits() + 1);
                break;
            }
        }
    }

    /**
     * 根据主键集合获取栏目对象
     *
     * @param primaryKeyList 主键集合
     * @return list
     */
    public List<CmsColumn> findColumnByPrimaryKeys(List<String> primaryKeyList) {
        if (null == primaryKeyList || primaryKeyList.isEmpty()) {
            return Collections.emptyList();
        }
        List<CmsColumn> columnList = mapper.findColumnByPrimaryKeys(primaryKeyList);
        return null == columnList ? Collections.emptyList() : columnList;
    }

    public Integer getTotalHitsBySiteId(String siteId) {
        return mapper.getTotalHitsBySiteId(siteId);
    }
}
